// 生成基于时间戳和当天序号的检测单编号
async function generateDetectionNo(detectTime, vk, db, _, excludeId = null) {
	// 解析检测时间
	let date = new Date(detectTime);
	let year = date.getFullYear();
	let month = String(date.getMonth() + 1).padStart(2, '0');
	let day = String(date.getDate()).padStart(2, '0');
	let hour = String(date.getHours()).padStart(2, '0');
	let minute = String(date.getMinutes()).padStart(2, '0');

	// 生成时间戳前缀 yyyyMMddHHmm (12位)
	let timePrefix = `${year}${month}${day}${hour}${minute}`;

	// 获取当天的开始和结束时间戳
	let dayStart = new Date(year, date.getMonth(), day, 0, 0, 0).getTime();
	let dayEnd = new Date(year, date.getMonth(), day, 23, 59, 59, 999).getTime();

	// 构建查询条件，基于detect_time字段查询当天的记录
	let whereJson = {
		detect_time: _.gte(dayStart).and(_.lte(dayEnd))
	};

	// 如果是更新操作，排除当前记录
	if (excludeId) {
		whereJson._id = _.neq(excludeId);
	}

	// 查询当天已有的检测单数量，基于detect_time字段
	let count = await vk.baseDao.count({
		dbName: "tm-detection-form",
		whereJson: whereJson
	});

	// 生成序号，从1开始，补齐到5位 (总长度17位: 12位时间戳 + 5位序号)
	let sequence = count + 1;
	let sequenceStr = String(sequence).padStart(5, '0');

	return timePrefix + sequenceStr;
}

module.exports = {
    /**
     * 批量添加检测单
     * @url admin/testing/detection-form/sys/batchadd 前端调用的url参数地址
     * data 请求参数 说明
     * @param {Array} batch_datas 批量添加的数据数组
     * res 返回参数说明
     * @param {Number} code 错误码，0表示成功
     * @param {String} msg 详细信息
     */
    main: async (event) => {
        let { data = {}, userInfo, util, filterResponse, originalParam } = event;
        let { customUtil, uniID, config, pubFun, vk, db, _ } = util;
        let { uid } = data;
        let res = { code: 0, msg: '' };
        // 业务逻辑开始-----------------------------------------------------------
        let { batch_datas } = data;

        for (let index = 0; index < batch_datas.length; index++) {
            const _addform = batch_datas[index];
            let info = await vk.baseDao.findByWhereJson({
                dbName: "uni-id-users",
                whereJson: {
                    nickname: _addform.detection_user,
                }
            });
            let detection_user_sign = undefined;
            if (vk.pubfn.isNotNull(info) && vk.pubfn.isNotNull(info.sign_image)) {
                detection_user_sign = info.sign_image
            }
            let sample_list=  JSON.parse(JSON.stringify(_addform.sample_list))
            delete _addform.sample_list;

            // 生成基于时间戳和当天序号的编号
            let no = await generateDetectionNo(_addform.detect_time, vk, db, _);

            let _addid = await vk.baseDao.add({
                dbName:'tm-detection-form',
                dataJson: {
                    no: no,
                    detection_user_sign: detection_user_sign,
                    ..._addform
                }
            });
            if (sample_list != undefined && sample_list.length > 0) {
                let _add_sample_list = sample_list.map(x => {
                    return {
                        'detectionform_id': _addid,
                        'client': _addform.client,
                        'client_name': _addform.client_name,
                        ...x
                    }
                })
                let ids = await vk.baseDao.adds({
                    dbName: "tm-sample-testing",// 表名
                    dataJson: _add_sample_list
                });
            }
    }
        // // 执行数据库API请求
        // res.count = await vk.baseDao.adds({
        //     dbName: "tm-detection-form",// 表名
        //     dataJson: batch_booths
        // });
        return res;
    }

}